import router from '../router'
import axios from 'axios'
import { Message } from 'element-ui'
import db from '../datastore'

axios.defaults.withCredentials = true

// 创建axios实例
const service = axios.create({
  headers: { 'Content-Type': 'application/json' },
  baseURL: '', // api的base_url
  timeout: 30000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  const userInfo = db.read().get('user').value()
  const authorizationToken = userInfo.token_type + ' ' + userInfo.access_token
  config.headers = {
    'Content-Type': 'application/json',
    'Authorization': authorizationToken
  }
  // 防止浏览器缓存参数
  const timeStr = new Date().getTime().toString()
  let url = config.url
  if (url.indexOf('_t') >= 0) {
    return config
  }
  if (url.indexOf('?') < 0) {
    url = url + '?_t=' + timeStr
  } else if (url.indexOf('?') >= 0) {
    url = url + '&_t=' + timeStr
  }
  config.url = url
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  // noinspection JSIgnoredPromiseFromCall
  Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200抛错 可结合自己业务进行修改
     */
    const data = response.data
    if (data.code !== 200) {
      Message({
        message: data.msg,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    // Http错误处理
    const status = error.response.status
    if (status === 401) {
      router.push({ path: '/login' })
      return Promise.reject(error)
    } else {
      Message({
        message: '后台服务出现问题，可能是没有启动',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  }
)

export default service
